import React from 'react';
import { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import axios from 'axios';
import Config from '../../Config';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import * as moment from 'moment';
import { useSelector } from 'react-redux';
import { selectUser } from '../../redux/Slice/userSlice';
import {
  Cascader,
  Spin,
  Layout,
  Image,
  Collapse,
  Row,
  Col,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  TimePicker,
} from 'antd';
const { Option } = Select;
const { TextArea } = Input;
const labelText = text => {
  return (
    <div
      style={{
        backgroundColor: '#FAFAFA',
        width: '120px',
        height: '31.6px',
        lineHeight: '31.6px',
        fontWeight: 'bold',
        fontSize: '15px',
        borderRadius: '3px',
        paddingRight: '5px',
      }}
    >
      {text}
    </div>
  );
};
export default forwardRef((props, ref) => {
  const [isLoading, setIsLoading] = useState(true);
  const [fieldNameMap, setFieldNameMap] = useState(new Map());
  const [departmentList, SetdepartmentList] = useState([]);
  const [placeList, SetplaceList] = useState([]);
  const [userList, SetUserList] = useState([]);
  const [refresh, SetReFresh] = useState(false);
  const [form] = Form.useForm();
  const [imgUrl, SetImgUrl] = useState('');

  const [JFKMOpt, SetJFKMOpt] = useState([]);
  const [XZOpt, SetXZOpt] = useState([]);
  const [XKLYOpt, SetXKLYOpt] = useState([]);
  const [SYFXOpt, SetSYFXOpt] = useState([]);
  const [GXMSOpt, SetGXMSOpt] = useState([]);

  let umap = new Map();
  let umap2 = new Map();
  let username = useSelector(selectUser);
  useImperativeHandle(ref, () => ({
    editFormValue,
    SetReFresh,
    refresh,
  }));
  const dfs2 = (node, data) => {
    let index = umap2.get(node.value);
    if (data[index].placeType === 1) return;

    let children = StringToArray(data[index].placeChildren);
    if (children.length == 0) return;
    node.children = [];
    for (let i = 0; i < children.length; i++) {
      let temp = {
        value: data[umap2.get(children[i])].placeId,
        label: data[umap2.get(children[i])].placeName,
      };
      node.children.push(temp);
      dfs2(temp, data);
    }
  };
  const placeTrans = data => {
    let root = [];
    for (let i = 0; i < data.length; i++) {
      umap2.set(data[i].placeId, i);
      if (data[i].placeParent == -1) root.push(i);
    }
    let ans = [];
    for (let k = 0; k < root.length; k++) {
      let res = {};
      res.value = data[root[k]].placeId;
      res.label = data[root[k]].placeName;
      let children = StringToArray(data[root[k]].placeChildren);
      res.children = [];
      for (let i = 0; i < children.length; i++) {
        let temp = {
          value: data[umap2.get(children[i])].placeId,
          label: data[umap2.get(children[i])].placeName,
        };
        res.children.push(temp);
        dfs2(temp, data);
      }
      ans.push(res);
    }
    return ans;
  };
  const StringToArray = str => {
    let arr = str.trim().split(/\s+/);
    if (arr == '') return [];
    return arr.map(val => {
      return parseInt(val);
    });
  };

  const dfs = (node, data) => {
    let index = umap.get(node.value);
    if (data[index].departmentType === 1) return;

    let children = StringToArray(data[index].departmentChildren);
    if (children.length == 0) return;
    node.children = [];
    for (let i = 0; i < children.length; i++) {
      let temp = {
        value: data[umap.get(children[i])].departmentId,
        label: data[umap.get(children[i])].departmentName,
      };
      node.children.push(temp);
      dfs(temp, data);
    }
  };
  const departmentTrans = data => {
    let root = [];
    for (let i = 0; i < data.length; i++) {
      umap.set(data[i].departmentId, i);
      if (data[i].departmentParent == -1) root.push(i);
    }
    let ans = [];
    for (let k = 0; k < root.length; k++) {
      let res = {};
      res.value = data[root[k]].departmentId;
      res.label = data[root[k]].departmentName;
      let children = StringToArray(data[root[k]].departmentChildren);
      res.children = [];
      for (let i = 0; i < children.length; i++) {
        let temp = {
          value: data[umap.get(children[i])].departmentId,
          label: data[umap.get(children[i])].departmentName,
        };
        res.children.push(temp);
        dfs(temp, data);
      }
      ans.push(res);
    }
    return ans;
  };
  const editFormValue = async () => {
    try {
      let val = await form.validateFields();
      val.GZRQ = val.GZRQ.format('YYYY-MM-DD');
      val.HGJGJZQ = val.HGJGJZQ.format('YYYY-MM-DD');
      val.BGRQ = val.BGRQ.format('YYYY-MM-DD');
      console.log(val);
      val.KFKSSJ = val.KFSJ[0].format('HH:mm');
      val.KFJSSJ = val.KFSJ[1].format('HH:mm');
      delete val.KFSJ;
      let deStr = '';
      let plStr = '';
      for (let i = 0; i < val.departmentId.length; i++) deStr += val.departmentId[i] + ' ';
      for (let i = 0; i < val.placeId.length; i++) plStr += val.placeId[i] + ' ';
      val.departmentId = deStr;
      val.placeId = plStr;
      for (let i in val) {
        if (val[i] == undefined) val[i] = '';
      }
      val.registerName = username;
      val.registerTime = moment().format('YYYY-MM-DD HH:mm:ss');
      val.imgUrl = imgUrl;
      return val;
    } catch (errInfo) {
      console.log(errInfo);
      message.error('数据不符合格式', 2);
    }
  };
  const transInstrument = val => {
    console.log(val);
    if (val.BGRQ != undefined) val.BGRQ = moment(val.BGRQ);
    if (val.GZRQ != undefined) val.GZRQ = moment(val.GZRQ);
    if (val.HGJGJZQ != undefined) val.HGJGJZQ = moment(val.HGJGJZQ);
    val.KFSJ = [];
    if (val.KFKSSJ != undefined && val.KFJSSJ != undefined) {
      val.KFSJ.push(moment(val.KFKSSJ, 'HH:mm'));
      val.KFSJ.push(moment(val.KFJSSJ, 'HH:mm'));
    }
    val.departmentId = StringToArray(val.departmentId);
    val.placeId = StringToArray(val.placeId);
    return val;
  };
  useEffect(() => {
    setIsLoading(true);
    console.log(props.curInfo);
    let instrumentUrl;
    if (props.curInfo.type == 2) instrumentUrl = 'getInstrumentCache';
    else instrumentUrl = 'getInstrument';
    axios
      .all([
        axios.get(Config.baseURL + '/instrument/fieldname').catch(err => {
          message.error('服务器出错', 2);
        }),
        axios.get(Config.baseURL + '/user/department').catch(error => {
          console.log(error);
          message.error('获取部门列表出错，请联系后台', 2);
        }),
        axios.get(Config.baseURL + '/place/allplace').catch(error => {
          console.log(error);
          message.error('获取存放地列表出错，请联系后台', 2);
        }),
        axios.get(Config.baseURL + '/user/alluser').catch(error => {
          console.log(error);
          message.error('获取管理人列表出错，请联系后台', 2);
        }),
        axios
          .post(Config.baseURL + '/instrument/' + instrumentUrl, {
            YQBH: props.curInfo.YQBH,
          })
          .catch(error => {
            console.log(error);
            message.error('获取仪器信息出错，请联系后台', 2);
          }),
        axios.get(Config.baseURL + '/dict/getInstrumentDict').catch(error => {
          console.log(error);
          message.error('获取字典列表出错，请联系后台', 2);
        }),
      ])
      .then(
        axios.spread((fieldName, department, place, user, instrument, dict) => {
          let res = department.data;
          if (res.code === 1) {
            let data = departmentTrans(res.data);
            SetdepartmentList(data);
          } else if (res.code >= 10000) {
            message.error('获取部门列表出错，请联系后台', 1);
          }
          let res3 = place.data;
          if (res3.code === 1) {
            console.log(res3.data);
            let data = placeTrans(res3.data);
            SetplaceList(data);
          } else if (res3.code >= 10000) {
            message.error('获取存放地列表出错，请联系后台', 2);
          }
          let res4 = user.data;
          if (res4.code === 1) {
            SetUserList(res4.data);
          } else if (res4.code >= 10000) {
            message.error('获取管理人列表出错，错误信息： ' + res.message, 2);
          }

          let res5 = instrument.data;
          if (res5.code === 1) {
            SetImgUrl(res5.data.imgUrl);
            form.setFieldsValue(transInstrument(res5.data));
          } else if (res5.code >= 10000) {
            message.error('获取仪器出错，错误信息： ' + res.message, 2);
          }

          let res6 = dict.data;
          if (res6.code === 1) {
            let data = res6.data;
            console.log(data);
            let arr1 = [];
            for (let val in data[0]) {
              arr1.push({
                label: data[0][val],
                value: val,
              });
            }
            let arr2 = [];
            for (let val in data[1]) {
              arr2.push({
                label: data[1][val],
                value: val,
              });
            }
            let arr3 = [];
            for (let val in data[2]) {
              arr3.push({
                label: data[2][val],
                value: val,
              });
            }
            let arr4 = [];
            for (let val in data[3]) {
              arr4.push({
                label: data[3][val],
                value: val,
              });
            }
            let arr5 = [];
            for (let val in data[4]) {
              arr5.push({
                label: data[4][val],
                value: val,
              });
            }

            SetJFKMOpt(arr1);
            SetXZOpt(arr2);
            SetSYFXOpt(arr3);
            SetXKLYOpt(arr4);
            SetGXMSOpt(arr5);
          } else if (res6.code >= 10000) {
            message.error('获取管理人列表出错，错误信息： ' + res.message, 2);
          }

          let fieldMap = new Map();
          for (let i = 0; i < fieldName.data.data.length; i++)
            fieldMap.set(fieldName.data.data[i].fieldName, fieldName.data.data[i].cnName);
          setFieldNameMap(fieldMap);

          setIsLoading(false);
        })
      );
  }, [refresh]);
  return (
    <Spin spinning={isLoading}>
      <Form form={form}>
        <Row gutter={[16, 5]}>
          <Col className="gutter-row" span={24}>
            <Form.Item label={labelText('仪器图片')}>
              <Image width={200} src={imgUrl} />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="YQMC"
              label={labelText(fieldNameMap.get('YQMC'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('YQMC') }]}
            >
              <Input disabled={props.disable} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="departmentId"
              label={labelText(fieldNameMap.get('departmentId'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('departmentId') }]}
            >
              <Cascader disabled={props.disable} changeOnSelect options={departmentList}></Cascader>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="placeId"
              label={labelText(fieldNameMap.get('placeId'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('placeId') }]}
            >
              <Cascader disabled={props.disable} options={placeList}></Cascader>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="LC"
              label={labelText(fieldNameMap.get('LC'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('LC') }]}
            >
              <Input disabled={props.disable} placeholder="请填写楼层，如第一层" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="FJM"
              label={labelText(fieldNameMap.get('FJM'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('FJM') }]}
            >
              <Input disabled={props.disable} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="SL"
              label={labelText(fieldNameMap.get('SL'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('SL') }]}
            >
              <Input disabled={props.disable} type={'number'} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="JE"
              label={labelText(fieldNameMap.get('JE'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('JE') }]}
            >
              <Input disabled={props.disable} type={'number'} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="GZRQ"
              label={labelText(fieldNameMap.get('GZRQ'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('GZRQ') }]}
            >
              <DatePicker
                disabled={props.disable}
                locale={locale}
                style={{ width: 257 }}
                size={'default'}
              />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="KFSJ"
              label={labelText(fieldNameMap.get('KFSJ'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('KFSJ') }]}
            >
              <TimePicker.RangePicker disabled={props.disable} locale={locale} format={'HH:mm'} />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="JFKM"
              label={labelText(fieldNameMap.get('JFKM'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('JFKM') }]}
            >
              <Select options={JFKMOpt} disabled={props.disable}></Select>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="XZ"
              label={labelText(fieldNameMap.get('XZ'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('XZ') }]}
            >
              <Select options={XZOpt} disabled={props.disable} style={{ width: 257 }}></Select>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="SYFX"
              label={labelText(fieldNameMap.get('SYFX'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('SYFX') }]}
            >
              <Select options={SYFXOpt} disabled={props.disable} style={{ width: 257 }}></Select>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item name="CJ" label={labelText(fieldNameMap.get('CJ'))} rules={[{}]}>
              <Input disabled={props.disable} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item name="GG" label={labelText(fieldNameMap.get('GG'))} rules={[{}]}>
              <Input disabled={props.disable} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="GLR"
              label={labelText(fieldNameMap.get('GLR'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('GLR') }]}
            >
              <Select disabled={props.disable}>
                {userList.map(value => {
                  return (
                    <Option key={value.id} value={value.id}>
                      {value.name}( {value.username} )
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="SFJK"
              label={labelText(fieldNameMap.get('SFJK'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('SFJK') }]}
            >
              <Select disabled={props.disable}>
                <Option value={0}>否</Option>
                <Option value={1}>是</Option>
              </Select>
            </Form.Item>
          </Col>
          {/* <Col className="gutter-row" span={8}>
            <Form.Item
              name="SFMS"
              label={labelText(fieldNameMap.get('SFMS'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('SFMS') }]}
            >
              <Select disabled={props.disable} placeholder="">
                <Option value={0}>否</Option>
                <Option value={1}>是</Option>
              </Select>
            </Form.Item>
          </Col> */}
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="HGJGJZQ"
              label={labelText(fieldNameMap.get('HGJGJZQ'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('HGJGJZQ') }]}
            >
              <DatePicker
                disabled={props.disable}
                locale={locale}
                style={{ width: 257 }}
                size={'default'}
              />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="BGRQ"
              label={labelText(fieldNameMap.get('BGRQ'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('BGRQ') }]}
            >
              <DatePicker
                disabled={props.disable}
                locale={locale}
                style={{ width: 257 }}
                size={'default'}
              />
            </Form.Item>
          </Col>
          {/* <Col className="gutter-row" span={8}>
            <Form.Item name="MSZH" label={labelText(fieldNameMap.get('MSZH'))} rules={[{}]}>
              <Input disabled={props.disable} placeholder="" />
            </Form.Item>
          </Col> */}
          {/* <Col className="gutter-row" span={8}>
            <Form.Item
              name="BGDH"
              label={labelText(fieldNameMap.get('BGDH'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('BGDH') }]}
            >
              <Input disabled={props.disable} placeholder="" />
            </Form.Item>
          </Col> */}
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="XKLY"
              label={labelText(fieldNameMap.get('XKLY'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('XKLY') }]}
            >
              <Select options={XKLYOpt} disabled={props.disable} style={{ width: 257 }}></Select>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="GXMS"
              label={labelText(fieldNameMap.get('GXMS'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('GXMS') }]}
            >
              <Select options={GXMSOpt} disabled={props.disable} style={{ width: 257 }}></Select>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="LXFS"
              label={labelText(fieldNameMap.get('LXFS'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('LXFS') }]}
            >
              <Input disabled={props.disable}></Input>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={8}>
            <Form.Item
              name="SFBZ"
              label={labelText(fieldNameMap.get('SFBZ'))}
              rules={[{ required: true, message: '需填写' + fieldNameMap.get('SFBZ') }]}
            >
              <Input disabled={props.disable} type={'number'} addonAfter="元每小时"></Input>
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={16}></Col>
          <Col className="gutter-row" span={24}>
            <Form.Item name="YPYQ" label={labelText(fieldNameMap.get('YPYQ'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={24}>
            <Form.Item name="YYSM" label={labelText(fieldNameMap.get('YYSM'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={24}>
            <Form.Item name="CSSM" label={labelText(fieldNameMap.get('CSSM'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={24}>
            <Form.Item name="ZYGN" label={labelText(fieldNameMap.get('ZYGN'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col>
          <Col className="gutter-row" span={24}>
            <Form.Item name="JSZB" label={labelText(fieldNameMap.get('JSZB'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col>
          {/* <Col className="gutter-row" span={24}>
            <Form.Item name="XJCD" label={labelText(fieldNameMap.get('XJCD'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col> */}
          {/* <Col className="gutter-row" span={24}>
            <Form.Item name="DXCG" label={labelText(fieldNameMap.get('DXCG'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col> */}
          <Col className="gutter-row" span={24}>
            <Form.Item name="BZ" label={labelText(fieldNameMap.get('BZ'))} rules={[{}]}>
              <TextArea disabled={props.disable} style={{ height: '70px' }} placeholder="" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Spin>
  );
});
